/**
 * 文件名    ： LoginImpl.java
 * 版权       : XX科技有限公司。
 * 描述       : <描述>
 * 修改时间：2018年11月14日
 * 修改内容：<修改内容>
 */
package com.example.demo.application.service.impl;

import java.util.List;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.example.demo.application.common.base.BaseServiceImpl;
import com.example.demo.application.common.encrypt.Byte2String;
import com.example.demo.application.common.encrypt.HmacSha256;
import com.example.demo.application.dao.IUserDao;
import com.example.demo.application.model.LoginUserEntity;
import com.example.demo.application.model.UserRepeateEntity;
import com.example.demo.application.service.IUserService;

/**
 * <功能>
 * @author    87431
 * @version   [版本号，2019年2月16日]
 * @see       [相关类/方法]
 * @since     [产品/模块版本]
 */
@Service(value = "userService")
public class UserServiceImpl extends BaseServiceImpl<LoginUserEntity>  implements IUserService {
	
    @Autowired  
    private IUserDao uDao;

	@Override
	public LoginUserEntity findUserById(LoginUserEntity user) throws Exception {
		LoginUserEntity dest = null;
		//根据账号查找，
		LoginUserEntity usersearch = new LoginUserEntity();
		usersearch.setAccount(user.getAccount());
		//1:有效 2: 临时。3: 第三方
		usersearch.setStatus("1");
		String originPasswd = user.getPasswd();
		if (StringUtils.isBlank(originPasswd)) {
			return null;
		}
		List<LoginUserEntity> list = uDao.findUserByParams(usersearch);
		if (null != list && list.size() > 0) {
			for (LoginUserEntity loginUserEntity : list) {
				String destPasswd = loginUserEntity.getPasswd();
				String salt = loginUserEntity.getSalt();
				//加密  对比 密文串
				String destEncrypt = Byte2String.byteArrayToHexString(HmacSha256.hmac_sha256(originPasswd, salt));
				if (destPasswd.equals(destEncrypt)) {
					dest = loginUserEntity;
					//登录成功 的token
					String token = UUID.randomUUID().toString().replace("-","");
					dest.setToken(token);
					break;
				}
			}
		}
		return dest;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int addUser(LoginUserEntity obj) throws Exception {
		String salt = UUID.randomUUID().toString().replace("-","");
		obj.setSalt(salt);
		//1:有效
		obj.setStatus("1");
		//哈希加密
		obj.setPasswd(Byte2String.byteArrayToHexString(HmacSha256.hmac_sha256(obj.getPasswd(), salt)));
		
		uDao.addUser(obj);
		return 1;
	}  
    
    public LoginUserEntity update(UserRepeateEntity user) throws Exception {
    	LoginUserEntity dest = findUserById(user);
    	if (null != dest) {
    		dest.setPasswd(Byte2String.byteArrayToHexString(HmacSha256.hmac_sha256(user.getPasswd2(), dest.getSalt())));
		}else {
			return null;
		}
    	return super.update(dest);
    }

}
